
function init() {
    //OpenLayers.IMAGE_RELOAD_ATTEMPTS = 2;
    OpenLayers.Util.onImageLoadErrorColor = "transparent"; 
    //Parámetros obtenidos desde la grilla de capas
    var layer = $('#layer').val();
    var srs = $('#srs').val();
    var format = $('#format').val();
    var bbox = $('#bbox').val();
    var bboxArr = bbox.split(' ');
    var popups = {};
   
    $.ajax({
        url: APPALIAS+'/viewLayer/getSRSResolutions/'+encodeURIComponent(srs),
        type: 'GET',
       
        dataType: 'json',
        success: function(data){
            // obtengo el bbox y las resoluciones  srs (debe machear cuando defino la capa)
            var resolutions = $.map(data.resolutions, function (res) {
                return parseFloat(res);
            });
            
            // límites de zoom 
            var minZoomLevel = parseInt($("#minZoomLevel").val());
            var maxZoomLevel = parseInt($("#maxZoomLevel").val());
            
            var limitedResolutions = [];
    
            limitedResolutions = resolutions.slice(minZoomLevel,maxZoomLevel);
            
            // boundingBox de la capa
            var srsExtentArray = data.extent;
    
            var navhis= new OpenLayers.Control.NavigationHistory();
            
    
            var extent = new OpenLayers.Bounds(bboxArr[0],bboxArr[1],bboxArr[2], bboxArr[3]);
            var srsExtent = new OpenLayers.Bounds(parseFloat(srsExtentArray.minX),parseFloat(srsExtentArray.minY),parseFloat(srsExtentArray.maxX), parseFloat(srsExtentArray.maxY));
            var mapProjection = new OpenLayers.Projection(srs.toUpperCase());
            
            var map = new OpenLayers.Map( 'map', {
                //restrictedExtent:  extent,
                projection: mapProjection,
                displayProjection: mapProjection,
                resolutions: limitedResolutions,
                controls: [
                new OpenLayers.Control.Navigation(),
                new OpenLayers.Control.Attribution(),
                new OpenLayers.Control.PanZoomBar(),
                new OpenLayers.Control.LayerSwitcher({
                    'ascending':false
                }),
                navhis,
                new OpenLayers.Control.ScaleLine({
                    geodesic: true
                }),
                new OpenLayers.Control.MousePosition({
                    separator: ' | ',
                    numDigits: 4,
                    emptyString: 'Fuera del mapa'
                }),

               
                new OpenLayers.Control.KeyboardDefaults()
                ],
                allOverlays:false
                
            } );
            var zoomControl = new OpenLayers.Control.Zoom({
                div: document.getElementById('zoomControl')
            });
            var panel = new OpenLayers.Control.Panel(
            {
                div: document.getElementById("panel")
            }
            ); 
            panel.addControls([ navhis.previous, navhis.next ]);
            map.addControl(panel);
            
      
            
            var wmts_layer = new OpenLayers.Layer.WMTS({
                name: layer+'-'+srs+'-WMTS',
                url: "/map.fcgi/wmts/",
                layer: layer,
                matrixSet: srs,
                //requestEncoding: 'REST',
                format: format,
                style: 'default',
                gutter:0,
                buffer:0,
                isBaseLayer:true,
                transitionEffect:'resize',
                resulutions: limitedResolutions,
                zoomOffset:minZoomLevel,
                maxExtent: srsExtent,
                projection: mapProjection,
                sphericalMercator: false
            }
            );
            
            // getFeatureInfo Control
            var getFeatureInfoControl = new OpenLayers.Control.WMTSGetFeatureInfo({
                drillDown: true,
                queryVisible: true,
                //requestEncoding:'REST',
                
                eventListeners: {
                    getfeatureinfo: function(evt) {
                        var text;
                        var match = evt.text.match(/<body[^>]*>([\s\S]*)<\/body>/);
                        if (match && !match[1].match(/^\s*$/)) {
                            text = match[1];
                        } else {
                            text = "No " + evt.layer.name + " features in that area.<br>";
                        }
                        var popupId = evt.xy.x + "," + evt.xy.y;
                        var popup = popups[popupId];
                        if (!popup || !popup.map) {
                            popup = new OpenLayers.Popup.FramedCloud(
                                popupId, 
                                map.getLonLatFromPixel(evt.xy),
                                null,
                                " ",
                                null,
                                true,
                                function(evt) {
                                    delete popups[this.id];
                                    this.hide();
                                    OpenLayers.Event.stop(evt);
                                }
                                );
                            popups[popupId] = popup;
                            map.addPopup(popup, true);
                        }
                        popup.setContentHTML(popup.contentHTML + text);
                        popup.show();
                    }
                }
            });
           
            map.addLayers([wmts_layer]);
               
            map.addControl(getFeatureInfoControl);
            getFeatureInfoControl.activate();
           
            map.addControl(new OpenLayers.Control.LayerSwitcher());

            map.events.register("zoomend", map, function(e){
                updateScale(e);
            });
        
            var from = new OpenLayers.Projection("EPSG:4326");
            var center = new OpenLayers.LonLat(-61.389770507812, -31.690014648437);
            map.setCenter(center.transform(from,mapProjection));
            
            //if(!map.getCenter())
            //map.zoomTo(minZoomLevel);
            $('#currentScale').val(map.getScale());
            $('#currentZoomLevel').val(map.getZoom()+ parseInt($("#minZoomLevel").val()));
   
        },
        error: function(){
            createDialog('Aviso','Error al obtener información de la capa',function(){
                window.location.href='layers'
            });  
        }
    });

};

function updateScale(e) {
    $('#currentScale').val(e.object.getScale());
    $('#currentZoomLevel').val(parseInt(e.object.getZoom()) + parseInt($("#minZoomLevel").val()));
}



$(document).ready(function () {
    init();
    OpenLayers.Popup.FramedCloud.prototype.maxSize = new OpenLayers.Size(500, 200);
});